package com.tanhua.admin.service;

import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.model.domain.Analysis;
import com.tanhua.model.dto.DiagramDto;
import com.tanhua.model.vo.DiagramVo;
import com.tanhua.model.vo.SummaryVo;
import com.tanhua.model.vo.YearVo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by ZhaoJun on 2022/1/6 20:07
 */
@Service
public class DashboardService {

    @Autowired
    private AnalysisMapper analysisMapper;

    /**
     * 展示次日流程，活跃，新增用户数据统计
     * @param dto
     * @return
     * @throws ParseException
     */

    public DiagramVo getDiagram(DiagramDto dto) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date dateS = new Date(Long.valueOf(dto.getSd()));
        Date dateE = new Date(Long.valueOf(dto.getEd()));
        String sd = sdf.format(dateS);
        String ed = sdf.format(dateE);
        String type = dto.getType();

        //得到去年同期时间
        //string和date的解析和格式，以及获得去年同期时间的方法
        Calendar c = Calendar.getInstance();
        c.setTime(dateS);
        c.add(Calendar.YEAR, -1);
        String lsd = sdf.format(c.getTime());

        c.setTime(dateE);
        c.add(Calendar.YEAR, -1);
        String led = sdf.format(c.getTime());

        List<Analysis> thisList = analysisMapper.thisYearRegisteredCount(sd,ed);
        List<Analysis> lastList = analysisMapper.thisYearRegisteredCount(lsd,led);
        DiagramVo vo = new DiagramVo();
        //判断thisYear的数据和封装
        if(CollectionUtils.isEmpty(thisList)){
            vo.setThisYear(new ArrayList<YearVo>());
        }else{
            //非null非空需要封装数据
            if("101".equals(type)){
                //1.查询时间段年内今年去年的注册用户总数
                List<YearVo> vos = thisList.stream().map(item -> {
                    return new YearVo(sdf.format(item.getRecordDate()), item.getNumRegistered());
                }).collect(Collectors.toList());
                vo.setThisYear(vos);
            }
            if("102".equals(type)){
                //1.查询时间段年内今年去年的注册用户总数
                List<YearVo> vos = thisList.stream().map(item -> {
                    return new YearVo(sdf.format(item.getRecordDate()), item.getNumActive());
                }).collect(Collectors.toList());
                vo.setThisYear(vos);
            }
            if("103".equals(type)){
                //1.查询时间段年内今年去年的注册用户总数
                List<YearVo> vos = thisList.stream().map(item -> {
                    return new YearVo(sdf.format(item.getRecordDate()), item.getNumRetention1d());
                }).collect(Collectors.toList());
                vo.setThisYear(vos);
            }

        }

        //判断lastYear的数据和封装
        if(CollectionUtils.isEmpty(lastList)){
            vo.setLastYear(new ArrayList<YearVo>());
        }else{
            //非null非空需要封装数据
            if("101".equals(type)){
                //1.查询时间段年内今年去年的注册用户总数
                List<YearVo> vos = lastList.stream().map(item -> {
                    return new YearVo(sdf.format(item.getRecordDate()), item.getNumRegistered());
                }).collect(Collectors.toList());
                vo.setLastYear(vos);
            }
            if("102".equals(type)){
                //1.查询时间段年内今年去年的注册用户总数
                List<YearVo> vos = lastList.stream().map(item -> {
                    return new YearVo(sdf.format(item.getRecordDate()), item.getNumActive());
                }).collect(Collectors.toList());
                vo.setLastYear(vos);
            }
            if("103".equals(type)){
                //1.查询时间段年内今年去年的注册用户总数
                List<YearVo> vos = lastList.stream().map(item -> {
                    return new YearVo(sdf.format(item.getRecordDate()), item.getNumRetention1d());
                }).collect(Collectors.toList());
                vo.setLastYear(vos);
            }
        }

        return vo;

    }

    /**
     *可以展示累计用户，新增用户等数据。
     * 表字段--num_registered：注册人数、num_active：活跃、num_login：登录、num_retention1d：次日留存
     * @return
     */
    public SummaryVo summary() throws ParseException {
        // TODO: 2022/1/7 这部分数据要不要放在redis中
        //构建需要的时间参数
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        //当前时间
        Date datetoday = sdf.parse("2020-09-14");
//        Date datetoday = new Date();
        String today = sdf.format(datetoday);
        //昨日时间
        c.setTime(datetoday);
        c.add(Calendar.DATE,-1);
        String yesterday = sdf.format(c.getTime());
        //过去7天
        c.add(Calendar.DATE,-7);
        String passWeek = sdf.format(c.getTime());
        //过去30天
        c.add(Calendar.MONTH,-1);
        String passMonth = sdf.format(c.getTime());

        //1.获得累计注册用户 ps:(查询所有sum注册)
        Integer cumulativeUsers = analysisMapper.sumRegistered();
        if(cumulativeUsers == null){
            cumulativeUsers = 0;
        }
        //2.过去七天活跃用户 ps:(按时间段查询sum活跃)
        Integer activePassWeek = analysisMapper.sumActiveByPassDate(passWeek);
        if(activePassWeek == null){
            activePassWeek = 0;
        }
        //3.过去三十天活跃用户 ps:(按时间段查询sum活跃)
        Integer activePassMonth = analysisMapper.sumActiveByPassDate(passMonth);
        if(activePassMonth == null){
            activePassMonth = 0;
        }
        //4.今日新增用户 ps:(以下都是查询指定日期)
        Integer newUsersToday = analysisMapper.sumRegisteredByDate(today);
        Integer newUsersYesterday = analysisMapper.sumRegisteredByDate(yesterday);
        //计算新增用户涨跌率，单位百分数，正数为涨，负数为跌
        // 这里要做null或0的判断
        if(newUsersToday == null){
            newUsersToday = 0;
        }
        if(newUsersYesterday == null){
           newUsersYesterday = 0;
        }

        Integer newUsersUpDown = 0;

        if(newUsersYesterday != 0){
            newUsersUpDown = upDown(newUsersToday, newUsersYesterday);
        }

        //5.今日登录次数
        Integer loginTimesToday = analysisMapper.sumLoginByDate(today);
        Integer loginTimesYesterday = analysisMapper.sumLoginByDate(yesterday);
        //计算登录次数涨跌率，单位百分数，正数为涨，负数为跌
        //返回数据值判断
        if(loginTimesToday == null){
            loginTimesToday = 0;
        }
        if(loginTimesYesterday == null){
            loginTimesYesterday = 0;
        }

        Integer loginTimesUpDown = 0;

        if(loginTimesYesterday != 0){
            loginTimesUpDown = upDown(loginTimesToday, loginTimesYesterday);
        }
        //6.今日活跃用户
        Integer activeToday = analysisMapper.sumActiveByDate(today);
        Integer activeYesterday = analysisMapper.sumActiveByDate(yesterday);
        //计算活跃用户涨跌率，单位百分数，正数为涨，负数为跌
        //返回数据值判断
        if(activeToday == null){
            activeToday = 0;
        }
        if(activeYesterday == null){
            activeYesterday = 0;
        }

        Integer activeUpDown = 0;

        if(activeYesterday != 0){
            activeUpDown = upDown(activeToday, activeYesterday);
        }

        //构建返回对象
        SummaryVo summaryVo = SummaryVo.builder()
                .cumulativeUsers(cumulativeUsers)
                .activePassWeek(activePassWeek)
                .activePassMonth(activePassMonth)
                .newUsersToday(newUsersToday)
                .newUsersTodayRate(newUsersUpDown)
                .loginTimesToday(loginTimesToday)
                .loginTimesTodayRate(loginTimesUpDown)
                .activeUsersToday(activeToday)
                .activeUsersTodayRate(activeUpDown)
                .build();

        return summaryVo;
    }

    /**
     * 计算涨跌的方法
     * @param todayNum
     * @param yesterdayNum
     * @return
     */
    private Integer upDown(Integer todayNum,Integer yesterdayNum){

        return (todayNum - yesterdayNum)*100/yesterdayNum;

    }
}
